import React, { useState, useEffect } from 'react';
import { 
  Card, 
  Table, 
  Button, 
  Modal, 
  Form, 
  Input, 
  InputNumber, 
  Select, 
  message, 
  Space, 
  Popconfirm,
  Tabs,
  Switch,
  Tooltip
} from 'antd';
import { 
  PlusOutlined, 
  EditOutlined, 
  DeleteOutlined, 
  InfoCircleOutlined,
  ReloadOutlined 
} from '@ant-design/icons';
import { useAuth } from '../context/AuthContext';
import { usePermissions, PERMISSIONS } from '../utils/permissions';
import { configAPI, roleAPI } from '../utils/api';

const { TabPane } = Tabs;
const { Option } = Select;

const ConfigManagement = () => {
  const { user } = useAuth();
  const { hasPermission } = usePermissions(user);
  const [loading, setLoading] = useState(false);
  const [systemConfigs, setSystemConfigs] = useState([]);
  const [roleConfigs, setRoleConfigs] = useState([]);
  const [roles, setRoles] = useState([]);
  const [configTypes, setConfigTypes] = useState({}); // 新增：配置类型元数据
  const [modalVisible, setModalVisible] = useState(false);
  const [roleModalVisible, setRoleModalVisible] = useState(false);
  const [editingConfig, setEditingConfig] = useState(null);
  const [editingRoleConfig, setEditingRoleConfig] = useState(null);
  const [form] = Form.useForm();
  const [roleForm] = Form.useForm();
  const [activeTab, setActiveTab] = useState('system');
  const [countryMapping, setCountryMapping] = useState({});
  const [countryMappingLoading, setCountryMappingLoading] = useState(false);
  const [jsonInputValue, setJsonInputValue] = useState(''); // 用于管理JSON输入框的值

  const canManage = hasPermission(PERMISSIONS.CONFIG_MANAGE);
  const canView = hasPermission(PERMISSIONS.CONFIG_VIEW);
  


  // 移除硬编码的CONFIG_TYPES
  // const CONFIG_TYPES = { ... };

  useEffect(() => {
    if (canView) {
      fetchConfigTypes(); // 新增：获取配置类型
      fetchSystemConfigs();
      fetchRoleConfigs();
      fetchRoles();
      fetchCountryMapping();
    }
  }, [canView]);

  // 新增：获取配置类型元数据
  const fetchConfigTypes = async () => {
    try {
      const response = await configAPI.getConfigTypes();
      setConfigTypes(response);
    } catch (error) {
      console.error('获取配置类型失败:', error);
      message.error('获取配置类型失败');
    }
  };

  // 获取系统配置
  const fetchSystemConfigs = async () => {
    setLoading(true);
    try {
      const response = await configAPI.getSystemConfigs();
      // 直接使用返回的数组，不需要 response.configs
      setSystemConfigs(Array.isArray(response) ? response : []);
    } catch (error) {
      message.error('获取系统配置失败');
    } finally {
      setLoading(false);
    }
  };

  // 获取角色配置
  // 获取角色配置
  const fetchRoleConfigs = async () => {
    try {
      const response = await configAPI.getAllRoleConfigs(); // 改为获取所有角色配置
      // 直接使用返回的数组，不需要 response.configs
      setRoleConfigs(Array.isArray(response) ? response : []);
    } catch (error) {
      console.error('获取角色配置失败:', error);
      message.error('获取角色配置失败');
    }
  };

  // 获取角色列表
  const fetchRoles = async () => {
    try {
      const response = await roleAPI.getRoles();
      // 直接使用返回的数组，不需要 response.roles
      setRoles(Array.isArray(response) ? response : []);
    } catch (error) {
      message.error('获取角色列表失败');
    }
  };

  // 获取国家映射配置
  const fetchCountryMapping = async () => {
    setCountryMappingLoading(true);
    try {
      const response = await configAPI.getCountryMapping();
      setCountryMapping(response);
      setJsonInputValue(JSON.stringify(response, null, 2)); // 同步更新输入框的值
    } catch (error) {
      console.error('获取国家映射失败:', error);
      message.error('获取国家映射失败');
    } finally {
      setCountryMappingLoading(false);
    }
  };

  // 保存国家映射配置
  const handleSaveCountryMapping = async (newMapping) => {
    try {
      // 验证JSON格式
      if (!newMapping || typeof newMapping !== 'object') {
        throw new Error('无效的JSON格式');
      }

      // 检查数据格式：可能是 {country_mapping: {...}} 或者直接是 {...}
      let countryMappingData;
      if (newMapping.country_mapping && typeof newMapping.country_mapping === 'object') {
        // 格式：{country_mapping: {...}}
        countryMappingData = newMapping.country_mapping;
      } else if (Object.keys(newMapping).length > 0) {
        // 格式：直接是 {...}，检查是否都是数组
        let isValid = true;
        for (const [country, mappings] of Object.entries(newMapping)) {
          if (!Array.isArray(mappings)) {
            isValid = false;
            break;
          }
        }
        if (isValid) {
          countryMappingData = newMapping;
        } else {
          throw new Error('数据格式错误：每个国家的映射必须是数组');
        }
      } else {
        throw new Error('缺少有效的国家映射数据');
      }

      // 验证每个国家的映射数组
      for (const [country, mappings] of Object.entries(countryMappingData)) {
        if (!Array.isArray(mappings)) {
          throw new Error(`国家 "${country}" 的映射必须是数组`);
        }
        
        for (const mapping of mappings) {
          if (typeof mapping !== 'string') {
            throw new Error(`国家 "${country}" 的映射项必须是字符串`);
          }
        }
      }

      // 保存配置 - 调用后端API
      await configAPI.updateCountryMapping(countryMappingData);
      message.success('国家映射保存成功');
      setCountryMapping(newMapping);
    } catch (error) {
      console.error('保存国家映射失败:', error);
      message.error(error.message || '保存国家映射失败');
    }
  };

  // 保存系统配置
  const handleSaveSystemConfig = async (values) => {
    try {
      // 将config_value转换为字符串
      const configData = {
        ...values,
        config_value: String(values.config_value)
      };
      
      if (editingConfig) {
        await configAPI.updateSystemConfig(configData.config_key, {
          config_value: configData.config_value,
          description: configData.description
        });
        message.success('配置更新成功');
      } else {
        await configAPI.createSystemConfig(configData);
        message.success('配置添加成功');
      }
      setModalVisible(false);
      setEditingConfig(null);
      form.resetFields();
      fetchSystemConfigs();
    } catch (error) {
      message.error(error.response?.data?.detail || '操作失败');
    }
  };

  // 保存角色配置
  const handleSaveRoleConfig = async (values) => {
    try {
      // 将config_value转换为字符串
      const configData = {
        ...values,
        config_value: String(values.config_value)
      };
      await configAPI.createRoleConfig(configData);
      message.success('角色配置保存成功');
      setRoleModalVisible(false);
      setEditingRoleConfig(null);
      roleForm.resetFields();
      fetchRoleConfigs();
    } catch (error) {
      message.error(error.response?.data?.detail || '操作失败');
    }
  };

  // 删除角色配置
  const handleDeleteRoleConfig = async (roleId, configKey) => {
    try {
      await configAPI.deleteRoleConfig(roleId, configKey);
      message.success('角色配置删除成功');
      fetchRoleConfigs();
    } catch (error) {
      message.error('删除失败');
    }
  };

  // 更新系统配置表格列，使用动态获取的配置类型
  const systemColumns = [
    {
      title: '配置项',
      dataIndex: 'config_key',
      key: 'config_key',
      render: (key) => configTypes[key]?.label || key
    },
    {
      title: '配置值',
      dataIndex: 'config_value',
      key: 'config_value',
      render: (value, record) => {
        const configType = configTypes[record.config_key];
        if (configType?.type === 'number' && value === '-1') {
          return <span style={{ color: '#52c41a' }}>不限制</span>;
        }
        return value;
      }
    },
    {
      title: '描述',
      dataIndex: 'config_key',
      key: 'description',
      render: (key) => configTypes[key]?.description || '-'
    },
    {
      title: '更新时间',
      dataIndex: 'updated_at',
      key: 'updated_at',
      render: (time) => time ? new Date(time).toLocaleString() : '-'
    },
         ...(canManage ? [{
       title: '操作',
       key: 'action',
       render: (_, record) => (
         <Space>
           <Button
             type="link"
             icon={<EditOutlined />}
             onClick={() => {
               setEditingConfig(record);
               form.setFieldsValue(record);
               setModalVisible(true);
             }}
           >
             编辑
           </Button>
         </Space>
       )
     }] : [])
  ];

  // 更新角色配置表格列
  const roleColumns = [
    {
      title: '角色',
      dataIndex: 'role_id',
      key: 'role_id',
      render: (roleId) => {
        const role = roles.find(r => r.id === roleId);
        return role ? role.name : roleId;
      }
    },
    {
      title: '配置项',
      dataIndex: 'config_key',
      key: 'config_key',
      render: (key) => configTypes[key]?.label || key
    },
    {
      title: '配置值',
      dataIndex: 'config_value',
      key: 'config_value',
      render: (value, record) => {
        const configType = configTypes[record.config_key];
        if (configType?.type === 'number' && value === '-1') {
          return <span style={{ color: '#52c41a' }}>不限制</span>;
        }
        return value;
      }
    },
    {
      title: '更新时间',
      dataIndex: 'updated_at',
      key: 'updated_at',
      render: (time) => time ? new Date(time).toLocaleString() : '-'
    },
         ...(canManage ? [{
       title: '操作',
       key: 'action',
       render: (_, record) => (
         <Space>
           <Popconfirm
             title="确定删除这个角色配置覆盖吗？"
             onConfirm={() => handleDeleteRoleConfig(record.role_id, record.config_key)}
             okText="确定"
             cancelText="取消"
           >
             <Button
               type="link"
               danger
               icon={<DeleteOutlined />}
             >
               删除
             </Button>
           </Popconfirm>
         </Space>
       )
     }] : [])
  ];

  if (!canView) {
    return (
      <div style={{ padding: '24px', textAlign: 'center' }}>
        <h3>您没有权限访问此页面</h3>
      </div>
    );
  }

  return (
    <div style={{ padding: '24px' }}>
      <Card title="配置管理" extra={
        <Space>
          <Button 
            icon={<ReloadOutlined />} 
            onClick={() => {
              fetchSystemConfigs();
              fetchRoleConfigs();
            }}
          >
            刷新
          </Button>
        </Space>
      }>
        <Tabs activeKey={activeTab} onChange={setActiveTab}>
          <TabPane tab="系统配置" key="system">
            <div style={{ marginBottom: '16px' }}>
              {/* 移除添加配置按钮，因为系统配置是预定义的 */}
              {/* {canManage && (
                <Button
                  type="primary"
                  icon={<PlusOutlined />}
                  onClick={() => {
                    setEditingConfig(null);
                    form.resetFields();
                    setModalVisible(true);
                  }}
                >
                  添加配置
                </Button>
              )} */}
            </div>
            <Table
              columns={systemColumns}
              dataSource={systemConfigs}
              rowKey="config_key"
              loading={loading}
              scroll={{ x: 800, y: 400 }}
            />
          </TabPane>

          <TabPane tab="角色配置覆盖" key="role">
            <div style={{ marginBottom: '16px' }}>
                             {canManage && (
                 <Button
                   type="primary"
                   icon={<PlusOutlined />}
                   onClick={() => {
                     setEditingRoleConfig(null);
                     roleForm.resetFields();
                     setRoleModalVisible(true);
                   }}
                 >
                   添加角色配置
                 </Button>
               )}
            </div>
            <Table
              columns={roleColumns}
              dataSource={roleConfigs}
              rowKey={(record) => `${record.role_id}-${record.config_key}`}
              loading={loading}
              pagination={false}
            />
          </TabPane>

          <TabPane tab="国家映射配置" key="country">
            <div style={{ marginBottom: '16px' }}>
              <Space>
                <Button
                  type="primary"
                  icon={<ReloadOutlined />}
                  onClick={fetchCountryMapping}
                  loading={countryMappingLoading}
                >
                  刷新
                </Button>
                                 {canManage && (
                   <Button
                     type="primary"
                     icon={<PlusOutlined />}
                                        onClick={() => {
                     // 重置为默认的国家映射结构
                     const defaultMapping = {
                       "中国": ["China (CN)", "China", "中国"],
                       "美国": ["United States (US)", "United States", "美国"],
                       "日本": ["Japan (JP)", "Japan", "日本"]
                     };
                     setCountryMapping(defaultMapping);
                     setJsonInputValue(JSON.stringify(defaultMapping, null, 2));
                   }}
                   >
                     重置为默认
                   </Button>
                 )}
              </Space>
            </div>
            
                         {canManage ? (
              <div style={{ border: '1px solid #d9d9d9', borderRadius: '6px' }}>
                <Input.TextArea
                  value={jsonInputValue}
                  onChange={(e) => {
                    const inputValue = e.target.value;
                    setJsonInputValue(inputValue); // 总是更新输入框的值
                    
                    try {
                      const newValue = JSON.parse(inputValue);
                      setCountryMapping(newValue);
                    } catch (error) {
                      // JSON 格式错误时，仍然允许用户继续编辑
                      // 不更新 countryMapping 状态
                    }
                  }}
                  style={{ 
                    height: '500px', 
                    fontFamily: 'monospace',
                    fontSize: '12px'
                  }}
                  placeholder="请输入有效的JSON格式，例如：&#10;{&#10;  &quot;中国&quot;: [&quot;China (CN)&quot;, &quot;China&quot;, &quot;中国&quot;],&#10;  &quot;美国&quot;: [&quot;United States (US)&quot;, &quot;United States&quot;, &quot;美国&quot;]&#10;}"
                />
                <div style={{ padding: '16px', textAlign: 'center', borderTop: '1px solid #d9d9d9' }}>
                  <Space>
                                         <Button
                       type="primary"
                       onClick={() => {
                         try {
                           const parsedValue = JSON.parse(jsonInputValue);
                           handleSaveCountryMapping(parsedValue);
                         } catch (error) {
                           message.error('JSON格式错误，请检查输入');
                         }
                       }}
                     >
                       保存配置
                     </Button>
                    <Button onClick={fetchCountryMapping}>
                      取消
                    </Button>
                  </Space>
                </div>
              </div>
            ) : (
              <div style={{ border: '1px solid #d9d9d9', borderRadius: '6px', padding: '16px' }}>
                <pre style={{ margin: 0, whiteSpace: 'pre-wrap', wordBreak: 'break-word' }}>
                  {JSON.stringify(countryMapping, null, 2)}
                </pre>
              </div>
            )}
          </TabPane>
        </Tabs>
      </Card>

      {/* 系统配置编辑模态框 */}
      <Modal
        title={editingConfig ? "编辑系统配置" : "添加系统配置"}
        open={modalVisible}
        onCancel={() => {
          setModalVisible(false);
          setEditingConfig(null);
          form.resetFields();
        }}
        footer={null}
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSaveSystemConfig}
        >
          <Form.Item
            name="config_key"
            label="配置项"
            rules={[{ required: true, message: '请选择配置项' }]}
          >
            <Select placeholder="选择配置项" disabled={!!editingConfig}>
              {Object.entries(configTypes).map(([key, config]) => (
                <Option key={key} value={key}>
                  {config.label}
                  <Tooltip title={config.description}>
                    <InfoCircleOutlined style={{ marginLeft: 8, color: '#999' }} />
                  </Tooltip>
                </Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
            name="config_value"
            label="配置值"
            rules={[{ required: true, message: '请输入配置值' }]}
          >
            <InputNumber
              style={{ width: '100%' }}
              placeholder="输入配置值"
              min={(() => {
                const configKey = form.getFieldValue('config_key');
                return configKey && configTypes[configKey] ? configTypes[configKey].min : -1;
              })()}
              max={(() => {
                const configKey = form.getFieldValue('config_key');
                return configKey && configTypes[configKey] ? configTypes[configKey].max : undefined;
              })()}
            />
          </Form.Item>

          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">
                保存
              </Button>
              <Button onClick={() => {
                setModalVisible(false);
                setEditingConfig(null);
                form.resetFields();
              }}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>

      {/* 角色配置编辑模态框 */}
      <Modal
        title="添加角色配置覆盖"
        open={roleModalVisible}
        onCancel={() => {
          setRoleModalVisible(false);
          setEditingRoleConfig(null);
          roleForm.resetFields();
        }}
        footer={null}
        width={600}
      >
        <Form
          form={roleForm}
          layout="vertical"
          onFinish={handleSaveRoleConfig}
        >
          <Form.Item
            name="role_id"
            label="角色"
            rules={[{ required: true, message: '请选择角色' }]}
          >
            <Select placeholder="选择角色">
              {roles.map(role => (
                <Option key={role.id} value={role.id}>
                  {role.name}
                </Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
            name="config_key"
            label="配置项"
            rules={[{ required: true, message: '请选择配置项' }]}
          >
            <Select placeholder="选择配置项">
              {Object.entries(configTypes).map(([key, config]) => (
                <Option key={key} value={key}>
                  {config.label}
                  <Tooltip title={config.description}>
                    <InfoCircleOutlined style={{ marginLeft: 8, color: '#999' }} />
                  </Tooltip>
                </Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
            name="config_value"
            label="配置值"
            rules={[{ required: true, message: '请输入配置值' }]}
          >
            <InputNumber
              style={{ width: '100%' }}
              placeholder="输入配置值"
              min={(() => {
                const configKey = roleForm.getFieldValue('config_key');
                return configKey && configTypes[configKey] ? configTypes[configKey].min : -1;
              })()}
              max={(() => {
                const configKey = roleForm.getFieldValue('config_key');
                return configKey && configTypes[configKey] ? configTypes[configKey].max : undefined;
              })()}
            />
          </Form.Item>

          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">
                保存
              </Button>
              <Button onClick={() => {
                setRoleModalVisible(false);
                setEditingRoleConfig(null);
                roleForm.resetFields();
              }}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default ConfigManagement;